package chat;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;
/*java. net. Socket
封装了TCP协议,使用它就可以基于TCP协议
进行网络通讯
Socket是运行在客户端的*/

//聊天室客户端
public class Client {
    private Socket socket;



    /*构造方法，用来初始化客户端
    实例化Socket的时候需要传入两个参数:
    1:服务端地址:通过IP地址可以找到服务端那的
    计算机
    2:服务端端口:通过端口可以找到服务端计算机
    上的服 务端应用程序
    实例化Socket的过程就是连接的过程，若远端计
    算机没有响应会抛出异常.*/
    public Client() throws Exception{
        System.out.println("正在连接服务端");
        socket=new Socket("localhost",8088);
        System.out.println("与服务端建立连接");
    }

    public void Start(){
        try {

            Scanner scanner=new Scanner(System.in);


            String nikeName=null;

            while (true){
                System.out.println("请输入昵称");
                nikeName=scanner.nextLine();
                if (nikeName.length()>0){
                    break;
                }
                System.out.println("输入有误");
            }

            System.out.println("欢迎你"+nikeName+"开始聊天吧");
            /*Socket提供的方法:
            Outputstream getOutputStream
            获取一个字节输出流,通过该流写
            出的数据会被发送至远端计算机*/
            OutputStream outputStream =socket.getOutputStream();

            OutputStreamWriter outputStreamWriter=new OutputStreamWriter(outputStream,"UTF-8");

            PrintWriter printWriter=new PrintWriter(outputStreamWriter,true);


            //先发送个昵称
            printWriter.println(nikeName);

            ServerHandler serverHandler=new ServerHandler();
            Thread thread=new Thread(serverHandler);
            thread.start();

            while (true){
                printWriter.println(scanner.nextLine());
            }


        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        try{
            Client client=new Client();
            client.Start();

        }catch (Exception e){
            e.printStackTrace();
            System.out.println("客户端启动失败");
        }
    }



    //用来读服务端发来的消息
    class ServerHandler implements Runnable{
        @Override
        public void run() {
            try {
                InputStream inputStream=socket.getInputStream();
                InputStreamReader inputStreamReader=new InputStreamReader(inputStream,"UTF-8");
                BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
                String message=null;
                while ((message=bufferedReader.readLine())!=null){
                    System.out.println(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
